/*
 * @Description: 我的审核context
 * @Author: Rfan
 * @Date: 2023-02-10 11:12:31
 * @LastEditTime: 2023-02-28 10:42:09
 */

import { createContext, useContext, useReducer } from 'react';
import { MyApprovalsReducer } from '../reducers/MyApprovalsReducer';
import {
  HIDE_APPROVE_DIALOG,
  SET_APPROVE_LIST,
  SET_APPROVE_NAV,
  SET_LIST_QUERY,
  SHOW_APPROVE_DIALOG,
  SUBMIT_APPROVE
} from '../constants';
import {
  fetchBorrowProcessDetail,
  submitCurrentApprove,
  submitBorrowTask
} from '@/api/workFlow/workflow';
import { dealTaskApprove, dealTaskReject, fetchApprovalListByPage } from '@/api/workFlow/task';
import { appState } from '@/store/mobx';
import { taskStateList } from '../dictionaries';

const initialState = {
  listQuery: {
    pageNo: 1,
    pageSize: 10,
    param: {
      taskState: 0,
      flowType: ''
    }
  },
  // 利用审批列表
  approveList: [],
  taskStateList,
  // 选中的表格条目
  selectItems: [],

  approveDialog: {
    visible: false,
    data: null
  }
};

const MyApprovalsContext = createContext();

const MyApprovalsContextProvider = (props) => {
  const [state, dispatch] = useReducer(MyApprovalsReducer, initialState);

  const actions = {
    setListQuery(query) {
      dispatch({ type: SET_LIST_QUERY, data: query });
    },

    setApproveNav(navKey) {
      dispatch({ type: SET_APPROVE_NAV, navKey });
    },

    /**
     * @description: 获取审核任务列表
     * @param {any} query
     */
    getApprovalsList(query) {
      query.param.userId = appState.userInfo.id;
      return new Promise((resolve, reject) => {
        fetchApprovalListByPage(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: SET_APPROVE_LIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * @description: 打开查看申请弹窗
     */
    showApproveDialog(info, dialogType) {
      fetchBorrowProcessDetail(info.applyForm.id).then((res) => {
        const { data } = res;
        data.taskId = info.taskId;
        data.processInstanceId = info.processInstanceId;
        dispatch({ type: SHOW_APPROVE_DIALOG, data, dialogType });
      });
    },

    /**
     * @description: 打开查看申请弹窗
     */
    hideApproveDialog() {
      dispatch({ type: HIDE_APPROVE_DIALOG });
    },

    /**
     * @description: 提交借阅申请审核 - 老
     * @param {*} params
     */
    submitApprove(params) {
      submitBorrowTask(params).then((res) => {
        const { data } = res;
        dispatch({ type: SUBMIT_APPROVE, taskId: data.taskId });
      });
    },

    /**
     * @description: 提交申请
     * @param {IDealTaskParams} params
     * @param {1|2}submitType 提交类型，1 - 同意；2 - 拒绝
     */
    submitApprovalFunc(params, submitType) {
      const dealPromise = submitType === 1 ? dealTaskApprove(params) : dealTaskReject(params);
      return new Promise((resolve) => {
        dealPromise.then(() => {
          console.log('submit approval');
          dispatch({ type: HIDE_APPROVE_DIALOG, id: params.processInstanceId });
          resolve();
        });
      });
    },

    agreeApproveFun(params) {
      submitCurrentApprove(params).then((res) => {
        console.log('pass current approve', res.data);
      });
    }
  };

  const filters = {
    stateFilter(id) {
      return state.taskStateList.find((item) => item.id === id)?.name || '-';
    }
  };

  return (
    <MyApprovalsContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </MyApprovalsContext.Provider>
  );
};

export const useMyApprovalsContext = () => {
  return useContext(MyApprovalsContext);
};

export { MyApprovalsContext, MyApprovalsContextProvider };
